import 'dart:convert';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/a_elder/models/elder_entity.dart';
import 'package:ls_work/model/customer_info_model.dart';
import 'package:ls_work/net_configs.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/viewmodel/service_execute/service_execute_base_view_model.dart';

import '../../net/api/http_api.dart';
import '../../net/post_request.dart';
import '../../net/response/service_execute/service_execute_list_data.dart';

class NewServiceExecuteViewModel
    extends ServiceExecuteBaseViewModel<ServiceItem> {
  NewServiceExecuteViewModel(BuildContext context,
      {this.elderCode, this.customerElderId})
      : super(context);

  final String? elderCode;
  final String? customerElderId;

  var customerModel = CustomerInfoModel();
  ElderInfo? customerInfo;
  var planFinishDate = DateTime.now().toDateStr([yyyy, '-', mm, '-', dd]);

  var taskList = <ServiceTaskList>[];

  var selectIndex = 0;

  var selectItemList = <ServiceItem>[];

  ///可批量提交项目
  List<ServiceItem> get canBatchTask {
    var infoList = taskList[selectIndex].itemList;
    return infoList!
        .takeWhere<ServiceItem>((element) => element.canBatch)
        .toList();
  }

  ///单独处理项目
  List<ServiceItem> get singleTask {
    var infoList = taskList[selectIndex].itemList;
    return infoList!
        .takeWhere<ServiceItem>((element) => !element.canBatch)
        .toList();
  }

  Future<List<ServiceItem>> requestListData() async {
    selectIndex = 0;
    selectItemList.clear();
    if (customerInfo == null) {
      customerInfo = await customerModel.getElderInfo(customerElderId!);
    }
    var result = await PostRequest.newOldServicePlanList(
        elderCode, customerElderId, planFinishDate, "0");
    if ("0" == result['code']) {
      var list = ((result['data']['rows'] as List?)??[])
          .map((e) => ServiceExecuteListData.fromJson(e))
          .toList();
      // list.sort((o1, o2) {
      //   return o1.planStartTime.compareTo(o2.planStartTime);
      // });
      // list.sort((o1, o2) {
      //   return (o1.planTimeFlag ?? 0).compareTo(o2.planTimeFlag ?? 0);
      // });

      var itemList = formatList(list);
      taskList = getTypeData(itemList);
      return itemList;
    } else {
      throw result['msg'].toString();
    }
  }

  @override
  void onCreated() {
    super.onCreated();
    requestRefresh(showAni: false);
  }

  void inputClick(ServiceItem item) {
    var task = (item.taskList??[]).first;
    onExecuteClick(task.id!);
  }

  void showClearApplyDialog(ServiceItem item) {
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: Text("操作提示"),
            content: Text(
                "\n当前页面已经有选中项目未提交完成任务，本任务为单项执行任务，点击“继续”后，已选中项目将会被清空，并且进入单项执行界面",
            style: TextStyle(fontSize: 15,color: Colors.black),),
            actions: [
              TextButton(
                  onPressed: () {
                    Go().pop();
                  },
                  child: Text('取消',style: TextStyle(color: Colors.grey[700],fontSize: 16),)),
              TextButton(
                  onPressed: () {
                    Go().pop();
                    clearSelectBatch();
                    inputClick(item);
                  },
                  child: Text('继续',style: TextStyle(fontSize: 16))),
            ],
          );
        });
  }

  void clearSelectBatch() {
    selectItemList.clear();
    notifyListeners();
  }

  void showApplyBatchDialog(){
    showCupertinoDialog(context: context, builder: (context){
      return Dialog(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(height: 15,),
            CommonText('任务执行确认',textSize: 17,fontWeight: FontWeight.bold),
            SizedBox(height: 12,),
            Divider(height: 1,color: Colors.grey,),
            SizedBox(height: 12,),
            Row(
              children: [
                SizedBox(width: 12,),
                CommonText('序号').setWeight(1),
                CommonText('服务项目').setWeight(2),
                SizedBox(width: 12,),
              ],
            ),
            SizedBox(height: 10,),
            ...List.generate(selectItemList.length, (index) {
              return Row(
                children: [
                  SizedBox(width: 12,),
                  CommonText('${index+1}').setWeight(1),
                  CommonText('${selectItemList[index].itemName}').setWeight(2),
                  SizedBox(width: 12,),
                ],
              ).addToContainer(margin: EdgeInsets.only(bottom: 10));
            }),
            Row(
              children: [
                SizedBox(width: 12,),
                TextButton(onPressed: (){
                  Go().pop();
                }, child: CommonText('取消',textColor: Colors.grey[600]!),style: ButtonStyle(
                  shape: WidgetStateProperty.all(RoundedRectangleBorder(
                    side: BorderSide(color: Colors.grey[600]!),
                    borderRadius: 4.borderRadius
                  ))
                ),).setWeight(1),
                SizedBox(width: 12,),
                TextButton(onPressed: (){
                  Go().pop();
                  batchSubmit();
                }, child: CommonText('提交',textColor: Colors.white),style: ButtonStyle(
                  backgroundColor: WidgetStateProperty.all(Colors.blue),
                  shape: WidgetStateProperty.all(RoundedRectangleBorder(borderRadius: 4.borderRadius))
                ),).setWeight(1),
                SizedBox(width: 12,),
              ],
            )
          ],
        ),
        
      );
    });
  }

  Future<void> batchSubmit() async {
    List tempList = [];
    for (var serviceItem in selectItemList) {
      var item = (serviceItem.taskList??[]).first;
      Map<String, dynamic> map = {};
      map["id"] = item.id;
      map["executeStatus"] = 0;
      map["finishTime"] =
          DateTime.now().toDateStr([yyyy,'-',mm,'-',dd,' ',HH,':',nn,':',ss]);
      map["remark"] = item.remark;
      if (item.bizParams.length > 0) {
        var temp = [];
        for (var i = 0; i < item.bizParams.length; i++) {
          temp.add({
            'value': "",
            'rangeTo': item.bizParams[i].rangeTo ?? "",
            'rangeFrom': item.bizParams[i].rangeFrom ?? "",
            'subItem': item.bizParams[i].subItem,
          });
        }
        map['result'] = jsonEncode(temp);
      }
      tempList.add(map);
    }
    showLoadingDialog(msg: '提交中...');
    try{
      var result = await HttpGo.instance.postData(HttpApi.executeServicePlanRecordBatch,data:{"jsonStr":jsonEncode(tempList)},options:
      PostRequest.urlencodedHeader);
      hideDialog();
      if("0"==result['code'].toString()){
        requestRefresh();
      }else{
        showToast(result['msg'].toString());
      }
    }catch(e){
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }

  List<ServiceItem> formatList(List<ServiceExecuteListData> list) {
    var typeMap = <String, List<ServiceExecuteListData>>{};
    for (var item in list) {
      if (typeMap[item.expenseItem] == null) {
        typeMap[item.expenseItem!] = [item];
      } else {
        typeMap[item.expenseItem]!.add(item);
      }
    }
    var itemList = typeMap.entries.map((e) {
      var itemData = e.value.first;
      return ServiceItem(
          itemName: itemData.expenseItem,
          typeName: itemData.expenseTypeName,
          taskList: e.value,
          image: itemData.itemImg,
          canBatch: itemData.resultMode == 0);
    }).toList();
    print(itemList.length);
    return itemList;
  }

  List<ServiceTaskList> getTypeData(List<ServiceItem> list) {
    var typeMap = <String, List<ServiceItem>>{};
    for (var item in list) {
      if (typeMap[item.typeName] == null) {
        typeMap[item.typeName!] = [item];
      } else {
        typeMap[item.typeName]!.add(item);
      }
    }
    var itemList = typeMap.entries.map((e) {
      return ServiceTaskList(name: e.key, itemList: e.value);
    }).toList();
    itemList.insert(0, ServiceTaskList(name: "全部", itemList: list));
    return itemList;
  }
}

class ServiceTaskList {
  String? name;

  List<ServiceItem>? itemList;

  num get count {
    var number = 0;
    for (var item in (itemList??<ServiceItem>[])) {
      number += (item.taskList??[]).length;
    }
    return number;
  }

  ServiceTaskList({this.name, this.itemList});
}

class ServiceItem {
  String? itemName;
  dynamic image;
  String? typeName;
  bool canBatch;
  List<ServiceExecuteListData>? taskList;

  ServiceItem(
      {this.itemName,
      this.image,
      this.taskList,
      this.typeName,
      this.canBatch = false});
}
